package pl.edu.agh.experts.diseases;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;

import pl.edu.agh.experts.diseases.gui.Setup;
import pl.edu.agh.experts.diseases.gui.SetupWindow;

public class Main {

	private static final InterfaceType interfaceType = InterfaceType.GUI;

	public static final void main(String[] args) {

		KnowledgeBase kbase = null;
		KnowledgeBase kbaseResults = null;
		try {
			kbase = readKnowledgeBase("DiseaseRules.drl");
			kbaseResults = readKnowledgeBase("DecisionRules.drl");
		} catch (Exception e) {
			System.out.println("Wystąpił krytyczny błąd, program się zakończy");
			e.printStackTrace();
			System.exit(1);
		}

		DiseaseHolder diseaseHolder = new DiseaseHolder();

		QuestionProvider questionProvider = new QuestionProvider(kbase, kbaseResults,
				diseaseHolder, new QuestionStrategyProvider(QuestionStrategy.BestFit), interfaceType);
		if (interfaceType == InterfaceType.Console) {
			boolean askNextQuestion = true;
			while (askNextQuestion) {
				askNextQuestion = questionProvider.askPatient();
			}
			Printer.printResults(diseaseHolder.getAllDiseases());
		}
		else if(interfaceType == InterfaceType.GUI) {
			Setup.setQuestionProvider(questionProvider);
			new SetupWindow();
		}
	}

	private static KnowledgeBase readKnowledgeBase(String ruleFile) throws Exception {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		kbuilder.add(ResourceFactory.newClassPathResource(ruleFile), ResourceType.DRL);
		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		if (errors.size() > 0) {
			for (KnowledgeBuilderError error : errors) {
				System.err.println(error);
			}
			throw new IllegalArgumentException("Could not parse knowledge.");
		}
		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		return kbase;
	}
}
